package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Files {

    private static final int BUF_SIZE = 0x1000; // 4K

    public static void copy(File from, File to) throws IOException {
        FileInputStream input = new FileInputStream(from);
        FileOutputStream output = new FileOutputStream(to);
        byte[] buf = new byte[BUF_SIZE];
        while (true) {
            int r = input.read(buf);
            if (r == -1) {
                break;
            }
            output.write(buf, 0, r);
        }
        
        input.close();
        output.close();
    }

    public static void move(File from, File to) throws IOException {
        if (!from.renameTo(to)) {
            copy(from, to);
            if (!from.delete()) {
                if (!to.delete()) {
                    throw new IOException("Unable to delete " + to);
                }
                throw new IOException("Unable to delete " + from);
            }
        }
    }

}
